<?php
declare (strict_types = 1);

namespace app\adminapi\middleware\http;

use app\adminapi\cache\AdminTokenCache;
use think\Event;
use think\exception\HttpException;
use app\adminapi\service\AdminTokenService;
use adminmatrix\admin\service\JsonService;
use think\facade\Config;
class LoginMiddleware
{
    protected bool $permission;
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $token = $request->header('token');
        if (!$request->permission && empty($token))
            throw new HttpException(401, '请先登录');

        $adminInfo = ( new AdminTokenCache ) ->getAdminInfo($token);
        if (empty($adminInfo) && !$request->permission)
            throw new HttpException(401 , '登录超时,请重新登陆');


        if ($adminInfo)
        {

            //获取临近过期自动续期时长
            $beExpireDuration = Config::get('project.admin_token.be_expire_duration');
            //token续期
            if (time() > ($adminInfo['expire_time'] - $beExpireDuration)) {
                $result = AdminTokenService::overtimeToken($token);
                //续期失败（数据表被删除导致）
                if (empty($result)) {
                    return JsonService::fail('登录过期', [], -1);
                }
            }

        }


        $request->adminInfo = $adminInfo;
        $request->admin_id  = $adminInfo['admin_id'] ?? 0;
        return  $next($request);
    }

}
